package com.skivingcloud.report.datas.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.skivingcloud.report.congfig.DatasourceProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skivingcloud.report.datas.entity.ReportDataSource;
import com.skivingcloud.report.datas.service.IJdbcService;

import javax.sql.DataSource;

@Service
public class JdbcServiceImpl implements IJdbcService {

	private static Logger log = LoggerFactory.getLogger(JdbcServiceImpl.class);

	@Autowired
    private DatasourceProperties datasourceProperties;
	/**
     * 所有数据源的连接池存在map里
     */
    private Map<String, DataSource> map = new ConcurrentHashMap<>();
    private Object lock = new Object();

	@Override
	public void removeJdbcConnectionPool(String id) {
		try {
            DataSource pool = map.get(id);
            if (pool != null) {
                log.info("remove pool success, datasourceId:{}", id);
                map.remove(id);
            }
        } catch (Exception e) {
            log.error("error", e);
        } finally {
        }
		
	}

	@Override
	public Connection getPooledConnection(ReportDataSource dataSource) throws SQLException {
		DataSource pool = getJdbcConnectionPool(dataSource);
        return pool.getConnection();
	}

	@Override
	public Connection getUnPooledConnection(ReportDataSource dataSource) throws SQLException {
		DataSource druidDataSource = datasourceProperties.dataSource(dataSource.getJdbcUrl(),
                dataSource.getUsername(), dataSource.getPassword(), dataSource.getDriverName());
        return druidDataSource.getConnection();
	}
    
	public DataSource getJdbcConnectionPool(ReportDataSource dataSource) {
        if (map.containsKey(dataSource.getId())) {
            return map.get(dataSource.getId());
        } else {
            try {
                synchronized (lock) {
                    if (!map.containsKey(dataSource.getId())) {
                        DataSource pool = datasourceProperties.dataSource(dataSource.getJdbcUrl(),
                                dataSource.getUsername(), dataSource.getPassword(), dataSource.getDriverName());
                        map.put(dataSource.getId(), pool);
                        log.info("创建连接池成功：{}", dataSource.getJdbcUrl());
                    }
                }
                return map.get(dataSource.getId());
            } finally {
            }
        }
    }
}